package com.cjm.one.common.result;


import com.cjm.one.common.result.ResultCodeEnum;
import lombok.Data;

/**
 * 全局统一返回结果类
 *
 */
@Data
public class Result<T> {

    //返回码
    private Integer code;

    //返回消息
    private String message;

    //返回数据
    private T data;

    public Result(){}

    // 返回数据
    protected static <T> Result<T> build(T data) {
        Result<T> result = new Result<T>();
        if (data != null)
            result.setData(data);
        return result;
    }

    public static <T> Result<T> build(T body, Integer code, String message) {
        Result<T> result = build(body);
        result.setCode(code);
        result.setMessage(message);
        return result;
    }

    public static <T> Result<T> build(T body, ResultCodeEnum resultCodeEnum) {
        Result<T> result = build(body);
        result.setCode(resultCodeEnum.getCode());
        result.setMessage(resultCodeEnum.getMessage());
        return result;
    }

    public static<T> Result<T> ok(){
        return Result.ok(null);
    }

    /**
     * 操作成功
     * @param data  baseCategory1List
     * @param <T>
     * @return
     */
    public static<T> Result<T> ok(T data){
        return build(data, ResultCodeEnum.SUCCESS);
    }

    public static<T> Result<T> fail(){
        return Result.fail(null);
    }

    /**
     * 操作失败
     * @param data
     * @param <T>
     * @return
     */
    public static<T> Result<T> fail(T data){
        return build(data, ResultCodeEnum.FAIL);
    }
    public static<T> Result<T> notAvailable(){
        return build(null, ResultCodeEnum.SERVICE_UNAVAILABLE);
    }

    public Result<T> message(String msg){
        this.setMessage(msg);
        return this;
    }

    public Result<T> code(Integer code){
        this.setCode(code);
        return this;
    }

    /**
     * 判断是否成功（根据ResultCodeEnum.SUCCESS的状态码判断）
     */
    public boolean isSuccess() {
        return ResultCodeEnum.SUCCESS.getCode().equals(this.code);
    }

    /**
     * 判断是否失败（与isSuccess()逻辑相反）
     */
    public boolean isFail() {
        return !isSuccess();
    }

    /**
     * 安全获取数据（失败时返回null）
     */
    public T getSafeData() {
        return isSuccess() ? this.data : null;
    }
    public static <T> Result<T> remoteSuccess(T data) {
        return build(data, ResultCodeEnum.SUCCESS);
    }

    public static <T> Result<T> remoteFail(String serviceName) {
        return build(null, ResultCodeEnum.REMOTE_SERVICE_ERROR.getCode(),
                "服务调用失败: " + serviceName);
    }

    public static <T> Result<T> remoteFail(ResultCodeEnum codeEnum, String message) {
        return build(null, codeEnum.getCode(), message);
    }
}
